﻿using CodeGenerator.Common;
using CodeGenerator.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace CodeGenerator
{
    public partial class frmLeft : DockContent
    {
        public delegate void NewContentForm(Connection conModel, string tableName, string databaseName, bool isView);
        public event NewContentForm newcontentForm;
        private List<Connection> list;
        public frmLeft()
        {
            InitializeComponent();
            base.ShowIcon = false;
            base.ShowInTaskbar = false;
            this.tview.ExpandAll();
        }

        private void frmLeft_Load(object sender, EventArgs e)
        {
            base.CloseButtonVisible = false;
            GetServers();
        }
        #region 私用方法
        private void GetServers()
        {
            this.tview.Nodes.Clear();
            this.tview.Nodes.Add("服务器", "服务器", 0);
            this.list = Utils.GetConnectionList();
            TreeNode node = this.tview.Nodes[0];
            node.ContextMenuStrip = this.cmstserve;
            foreach (Connection connection in this.list)
            {
                TreeNode node2 = new TreeNode(connection.Name, 0, 0)
                {
                    ContextMenuStrip = this.cmsdatabase,
                    Tag = connection.ID.ToString()
                };
                node.Nodes.Add(node2);
            }
            this.tview.ExpandAll();
        }

        private void  GetDatabaseinfo()
        {
            IDbObject obj2;
            TreeNode node = this.tview.SelectedNode;
            Connection connection = this.list.Find(con => con.ID.ToString().Equals(node.Tag.ToString()));
            DatabaseType msAccess = DatabaseType.SqlServer;
            msAccess = DatabaseType.SqlServer;
            if (connection.DbType.Equals((msAccess = DatabaseType.SqlServer).ToString()))
            {
                msAccess = DatabaseType.SqlServer;
                obj2 = new DbMSSQLObject(connection.ConnectionString);
                if (connection.Database.Equals("all"))
                {
                    DataTable dBList = obj2.GetDBList();
                    foreach (DataRow row in dBList.Rows)
                    {
                        TreeNode node3 = new TreeNode(row[0].ToString(), 1, 1)
                        {
                            Tag = connection.ConnectionString.Replace("master", row[0].ToString()),
                            ContextMenuStrip = this.cmsonedatabase
                        };
                        node.Nodes.Add(node3);
                        Gettables(node3, obj2.GetTables(node3.Text), obj2.GetVIEWs(node3.Text));
                    }
                }
                else
                {
                    TreeNode node4 = new TreeNode(connection.Database, 1, 1)
                    {
                        Tag = connection.ConnectionString,
                        ContextMenuStrip = this.cmsonedatabase
                    };
                    node.Nodes.Add(node4);
                    Gettables(node4, obj2.GetTables(node4.Text), obj2.GetVIEWs(node4.Text));
                }
            }
            else
            {
                msAccess = DatabaseType.MySql;
                if (connection.DbType.Equals(msAccess.ToString()))
                {
                    obj2 = new DbMySQLObject(connection.ConnectionString);
                    if (connection.Database.Equals("all"))
                    {
                        DataTable table2 = obj2.GetDBList();
                        foreach (DataRow row2 in table2.Rows)
                        {
                            TreeNode node6 = new TreeNode(row2[0].ToString(), 1, 1)
                            {
                                Tag = connection.ConnectionString.Replace("master", row2[0].ToString()),
                                ContextMenuStrip = this.cmsonedatabase
                            };
                            node.Nodes.Add(node6);
                            Gettables(node6, obj2.GetTables(node6.Text), obj2.GetVIEWs(node6.Text));
                        }
                    }
                    else
                    {
                        TreeNode node7 = new TreeNode(connection.Database, 1, 1)
                        {
                            Tag = connection.ConnectionString,
                            ContextMenuStrip = this.cmsonedatabase
                        };
                        node.Nodes.Add(node7);
                        Gettables(node7, obj2.GetTables(node7.Text), obj2.GetVIEWs(node7.Text));
                    }
                }
            }
        }

        private  void Gettables(TreeNode databaseNodel, DataTable tables, DataTable views)
        {
            TreeNode node = new TreeNode("表", 2, 2);
            if ((tables != null) && (tables.Rows.Count > 0))
            {
                DataRow[] rowArray = tables.Select("", "name asc");
                foreach (DataRow row in rowArray)
                {
                    TreeNode node3 = new TreeNode(row[0].ToString(), 3, 3)
                    {
                        Tag = "T",
                        ContextMenuStrip = this.cmstable
                    };
                    node.Nodes.Add(node3);
                }
            }
            databaseNodel.Nodes.Add(node);
            TreeNode node2 = new TreeNode("视图", 2, 2);
            if ((views != null) && (views.Rows.Count > 0))
            {
                DataRow[] rowArray3 = views.Select("", "name asc");
                foreach (DataRow row2 in rowArray3)
                {
                    TreeNode node4 = new TreeNode(row2[0].ToString(), 3, 3)
                    {
                        Tag = "V",
                        ContextMenuStrip = this.cmstable
                    };
                    node2.Nodes.Add(node4);
                }
            }
            databaseNodel.Nodes.Add(node2);
        }
        private void ShowDbSelect()
        {
            frmServer frmserver = new frmServer();
            if (frmserver.ShowDialog() == DialogResult.OK)
            {
                DialogResult no = DialogResult.No;
                DatabaseType? databaseType = frmServer.DatabaseType;
                if (databaseType.HasValue)
                {
                    switch (databaseType.GetValueOrDefault())
                    {
                        case DatabaseType.SqlServer:
                            no = new frmDBSqlServer().ShowDialog();
                            break;
                        case DatabaseType.MySql:
                            no = new frmDBMySql().ShowDialog();
                            break;
                    }
                }
                if (no == DialogResult.OK)
                {
                    this.RefreshConnectionList();
                }
            }
        }

        private void RefreshConnectionList()
        {
            List<Connection> connectionList = Utils.GetConnectionList();
            using (List<Connection>.Enumerator enumerator = connectionList.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    Connection conn = enumerator.Current;
                    if (this.list.Find(connin => conn.ID.ToString().Equals(connin.ID.ToString())) == null)
                    {
                        TreeNode node = new TreeNode(conn.Name, 0, 0)
                        {
                            ContextMenuStrip = this.cmsdatabase,
                            Tag = conn.ID.ToString()
                        };
                        this.tview.Nodes[0].Nodes.Add(node);
                    }
                }
            }
            this.list = connectionList;
        }
        #endregion

        //添加服务器
        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowDbSelect();
        }
        //刷新服务器
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshConnectionList();
        }
        //连接数据库
        private void 连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.tview.SelectedNode.Nodes.Clear();
            this.GetDatabaseinfo();
        }
        //删除数据库
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string stringid = this.tview.SelectedNode.Tag.ToString();
            Utils.DeleteConnection(stringid);
            Connection item = this.list.Find(conn => conn.ID.ToString().Equals(stringid));
            if (item != null)
            {
                this.list.Remove(item);
            }
            this.tview.Nodes.Remove(this.tview.SelectedNode);
        }
        //刷新数据库
        private void 刷新ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.tview.SelectedNode.Nodes.Clear();
            this.GetDatabaseinfo();
        }
        //批量生成
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            TreeNode node = this.tview.SelectedNode;
            Connection connection = this.list.Find(con => con.ID.ToString().Equals(node.Parent.Tag.ToString()));
            new frmBatch
            {
                DatabaseName = node.Text,
                ConnectionModel = connection
            }.ShowDialog();
            
           
        }
        //刷新数据库
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            IDbObject obj2;
            TreeNode node = this.tview.SelectedNode;
            node.Nodes.Clear();
            Connection connection = this.list.Find(con => con.ID.ToString().Equals(node.Parent.Tag.ToString()));
            DatabaseType msAccess = DatabaseType.SqlServer;
            if (connection.DbType.Equals(msAccess.ToString()))
            {
                obj2 = new DbMSSQLObject(connection.ConnectionString);
                this.Gettables(node, obj2.GetTables(node.Text), obj2.GetVIEWs(node.Text));
            }
            else
            {
                msAccess = DatabaseType.MySql;
                if (connection.DbType.Equals(msAccess.ToString()))
                {
                    obj2 = new DbMySQLObject(connection.ConnectionString);
                    this.Gettables(node, obj2.GetTables(node.Text), obj2.GetVIEWs(node.Text));
                }
            }

        }
        //生成代码
        private void 生成代码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.newcontentForm != null)
            {
                Connection conModel = this.list.Find(con => con.ID.ToString().Equals(this.tview.SelectedNode.Parent.Parent.Parent.Tag.ToString()));
                conModel.ConnectionString = this.tview.SelectedNode.Parent.Parent.Tag.ToString();
                this.newcontentForm(conModel, this.tview.SelectedNode.Text, this.tview.SelectedNode.Parent.Parent.Text, this.tview.SelectedNode.Tag.ToString().Equals("V"));
            }
        }


        private void tview_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ((TreeView)sender).SelectedNode = e.Node;
            }
        }
    }
}
